<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <script>
        let templateString = `
            <div >
                <h3 class='box' id="myBox">你好。</h3>
                <ul>
                    <li>可乐</li>
                    <li>啤酒</li>
                    <li>绿茶</li>
                </ul>
            </div>
        `;

        function parseHtml(string) {
            let index = 0;
            let beginTag = /^<\w+[0-6]?>/;
            let endTag = /^<\/\w+[0-6]?>/;
            let stringTag = /^[^<].*?</;
            let tagArr = [];
            let dataArr = [];
            string = string.replace(/ /g, '')
            string = string.replace(/\n/g, '')
            while (index < string.length - 1) {
                let str = string.slice(index);
                if (str.match(beginTag)) // 匹配开始标签
                {
                    let tag = str.match(beginTag)[0];
                    tagArr.push(tag)
                    dataArr.push([])
                    index += tag.length;
                    console.log("开始标签：", tag);
                } else if (str.match(endTag)) // 匹配结束标签
                {
                    let tag = str.match(endTag)[0];
                    // tagArr.push(tag)
                    let bTag = tagArr.pop();
                    if (bTag.slice(1) != tag.slice(2)) {
                        throw new Error("闭合标签有误~", bTag, tag)
                    }

                    dataArr[dataArr.length - 1].tag = tag.replace(/<|>|\//g, '')
                    let data = dataArr.pop();
                    if (dataArr.length > 0) {
                        if (!dataArr[dataArr.length - 1].hasOwnProperty('children')) {
                            dataArr[dataArr.length - 1].children = [];
                        }
                        dataArr[dataArr.length - 1].children.push(data);
                    } else {
                        return data
                    }
                    index += tag.length;

                    console.log("结束标签：", tag);
                } else if (str.match(stringTag)) // 匹配内置文本之类的
                {
                    let tag = str.match(stringTag)[0];
                    tag = tag.slice(0, tag.length - 1)
                    dataArr[dataArr.length - 1].push({ text: tag, type: 3 })
                    index += (tag.length);
                    console.log("内容标签：", tag);
                } else {
                    index++;
                    console.log("什么鬼。。。", str);
                }
                console.log(JSON.parse(JSON.stringify(tagArr)), JSON.parse(JSON.stringify(dataArr)));
            }
        }

        console.log(parseHtml(templateString));
    </script>
</body>

</html>